<template>
  <div class="user-edit-container">
    <a-card :bordered="false" class="user-edit-card">
      <template #title>
        <div class="title-container">
          <span class="title">👤 个人信息设置</span>
          <span class="update-time">上次更新：{{ userInfo?.updateTime || '暂无' }}</span>
        </div>
      </template>

      <a-spin :spinning="loading">
        <a-form :model="formState" :rules="rules" ref="formRef" layout="vertical" @finish="handleSubmit">
          <a-form-item label="头像" name="userAvatar">
            <div class="avatar-upload">
              <a-avatar :size="100" :src="formState.userAvatar" class="avatar-preview" />
              <a-upload v-model:file-list="fileList" :show-upload-list="false" :before-upload="beforeUpload"
                :custom-request="handleUpload">
                <a-button type="primary" class="upload-btn">
                  <upload-outlined /> 更换头像
                </a-button>
              </a-upload>
            </div>
          </a-form-item>

          <a-form-item label="用户名" name="userName">
            <a-input v-model:value="formState.userName" placeholder="请输入用户名" :maxLength="20">
              <template #prefix>
                <user-outlined />
              </template>
            </a-input>
          </a-form-item>

          <a-form-item label="个人简介" name="userProfile">
            <a-textarea v-model:value="formState.userProfile" placeholder="请输入个人简介" :maxLength="200"
              :auto-size="{ minRows: 3, maxRows: 6 }" />
          </a-form-item>

          <a-form-item>
            <a-space>
              <a-button type="primary" html-type="submit" :loading="submitting">
                <save-outlined /> 保存修改
              </a-button>
              <a-button @click="resetForm">
                <undo-outlined /> 重置
              </a-button>
            </a-space>
          </a-form-item>
        </a-form>
      </a-spin>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
import { message } from 'ant-design-vue'
import type { FormInstance } from 'ant-design-vue'
import {
  UserOutlined,
  UploadOutlined,
  SaveOutlined,
  UndoOutlined,
} from '@ant-design/icons-vue'
import {
  editUserUsingPost,
  getUserVoByIdUsingGet,
  getLoginUserUsingGet,
  uploadPictureUserUsingPost,
} from '@/api/userController'


const loading = ref(false)
const submitting = ref(false)
const formRef = ref<FormInstance>()
const fileList = ref<any[]>([])
const userInfo = ref<API.UserVO>()

const formState = reactive<API.UserEditRequest>({
  id: undefined,
  userName: '',
  userAvatar: '',
  userProfile: '',
})

const rules = {
  userName: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度在2-20个字符之间', trigger: 'blur' },
  ],
  userProfile: [
    { max: 200, message: '个人简介不能超过200个字符', trigger: 'blur' },
  ],
}

const fetchUserInfo = async () => {
  try {
    loading.value = true
    const res = await getLoginUserUsingGet()
    if (res.data.code === 0 && res.data.data) {
      const userId = res.data.data.id
      if (userId) {
        const userRes = await getUserVoByIdUsingGet({ id: userId })
        if (userRes.data.code === 0 && userRes.data.data) {
          const userInfo = userRes.data.data
          formState.id = userInfo.id
          formState.userName = userInfo.userName || ''
          formState.userAvatar = userInfo.userAvatar || ''
          formState.userProfile = userInfo.userProfile || ''
        }
      }
    }
  } catch (error) {
    message.error('获取用户信息失败')
  } finally {
    loading.value = false
  }
}

const handleSubmit = async () => {
  try {
    submitting.value = true
    const res = await editUserUsingPost(formState)
    if (res.data.code === 0) {
      message.success('保存成功')
      await fetchUserInfo()
    } else {
      message.error(res.data.message || '保存失败')
    }
  } catch (error) {
    message.error('保存失败，请稍后重试')
  } finally {
    submitting.value = false
  }
}

const resetForm = () => {
  formRef.value?.resetFields()
}

const beforeUpload = (file: File) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
  if (!isJpgOrPng) {
    message.error('只能上传JPG/PNG格式的图片！')
  }
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    message.error('图片大小不能超过2MB！')
  }
  return isJpgOrPng && isLt2M
}

const handleUpload = async ({ file }: any) => {
  try {
    loading.value = true
    const res = await uploadPictureUserUsingPost({}, file)
    if (res.data.code === 0 && res.data.data) {
      formState.userAvatar = res.data.data.url
      message.success('头像上传成功')
    } else {
      message.error(res.data.message || '头像上传失败')
    }
  } catch (error) {
    message.error('头像上传失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchUserInfo()
})
</script>

<style scoped>
.user-edit-container {
  padding: 24px;
  max-width: 800px;
  margin: 0 auto;
}

.user-edit-card {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.title-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  font-size: 24px;
  font-weight: bold;
}

.update-time {
  color: #999;
  font-size: 14px;
}

.avatar-upload {
  display: flex;
  align-items: center;
  gap: 24px;
}

.avatar-preview {
  border: 2px solid #f0f0f0;
  transition: all 0.3s;
}

.avatar-preview:hover {
  border-color: #1890ff;
}

.upload-btn {
  margin-top: 8px;
}

:deep(.ant-form-item-label) {
  font-weight: 500;
}

:deep(.ant-input-affix-wrapper) {
  border-radius: 4px;
}

:deep(.ant-input) {
  border-radius: 4px;
}

:deep(.ant-btn) {
  border-radius: 4px;
}

@media (max-width: 768px) {
  .user-edit-container {
    padding: 16px;
  }

  .avatar-upload {
    flex-direction: column;
    align-items: flex-start;
  }

  .title {
    font-size: 20px;
  }
}
</style>
